<template>
  <div>
    <el-row :gutter="10" type="flex" align="middle" style="margin-bottom: 10px">
      <el-col :span="3.5">
        <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽">
        </el-switch>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="draggable" type="primary" @click="saveBatch">批量保存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" @click="removeBatch">批量删除</el-button>
      </el-col>
    </el-row>
    <!-- 树形控件 -->
    <el-tree ref="menuTree" :data="menus" :props="defaultProps" show-checkbox :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop"
      node-key="catId" :default-expanded-keys="expandedKeys" :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => add(data)">
            新增
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            修改
          </el-button>
          <el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="category" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标地址">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Category",
  data() {
    return {
      title: "",
      menus: [],
      expandedKeys: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogFormVisible: false,
      category: {
        name: "",
        icon: "",
        productUnit: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
      },
      maxLevel: 0,
      draggable: false,
      pCids: [],
      updateNodes: [],
    };
  },
  mounted() {
    this.getMenuList();
  },
  methods: {
    // 获取数据列表
    getMenuList() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
    add(data) {
      console.log("data: ", data);
      this.title = "新增分类";
      this.category = {
        name: "",
        icon: "",
        productUnit: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
      };
      this.dialogFormVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
    },
    edit(data) {
      this.title = "修改分类";
      this.dialogFormVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log("回显数据: ", data);
        this.category = data.data;
      });
    },
    // 添加或者修改分类
    saveOrUpdateCategory() {
      console.log("category data: ", this.category);
      const { catId, name, icon, productUnit } = this.category;
      // 修改只需传 catId, name, icon, productUnit 这几个字段
      const data = this.category.catId ? { catId, name, icon, productUnit } : this.category;
      const url = this.category.catId ? "/product/category/update" : "/product/category/save";
      this.$http({
        url: this.$http.adornUrl(url),
        method: "post",
        data: this.$http.adornData(data, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: this.category.catId ? "修改成功!" : "新增成功!",
        });
        // 关闭对话框
        this.dialogFormVisible = false;
        // 刷新菜单
        this.getMenuList();
        // 设置需要默认展开的菜单
        this.expandedKeys = [this.category.parentCid];
      });
    },
    remove(node, data) {
      console.log("node: ", node, "data: ", data);
      let ids = [data.catId];
      this.$confirm(`是否确认删除分类名称为"${data.name}"的数据项?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 刷新菜单
            this.getMenuList();
            // 设置需要默认展开的菜单
            this.expandedKeys = [node.parent.data.catId];
          });
        })
        .catch(() => { });
    },
    // 批量删除
    removeBatch() {
      console.log("选中节点的数量: ", this.$refs.menuTree.getCheckedNodes().length);
      if (!this.$refs.menuTree.getCheckedNodes().length) {
        this.$message({
          type: "error",
          message: "请选择数据后操作!",
        });
        return;
      }
      const catIds = this.$refs.menuTree.getCheckedNodes().map((e) => e.catId);
      console.log("catIds: ", catIds);
      this.$confirm(`是否确认批量删除所选择的数据项?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "批量删除成功!",
            });
            // 刷新菜单
            this.getMenuList();
          });
        })
        .catch(() => { });
    },
    allowDrop(draggingNode, dropNode, type) {
      // 拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
      console.log(draggingNode, dropNode, type);
      this.maxLevel = 0;
      // 被拖动的当前节点以及所在的父节点总层数不能大于3
      this.countNodeLevel(draggingNode);
      // 计算被拖动节点的总层数
      let deep = this.maxLevel - draggingNode.level + 1;
      if (deep < 1) {
        deep = 1;
      }
      console.log("被拖动节点的总层数: ", deep);
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // 共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
      console.log(draggingNode, dropNode, dropType);
      // 1.当前节点最新的父节点id
      let pCid = 0;
      let siblings = null;
      if (dropType == "inner") {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else {
        pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }
      this.pCids.push(pCid);
      // 2.当前节点的最新顺序
      // 3.当前节点的最新层级
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          // 如果当前节点的层级发生了变化，只需把当前节点及其子节点的catLevel和level进行同步即可
          let catLevel = draggingNode.level;
          if (catLevel != siblings[i].level) {
            // 更新当前节点层级
            catLevel = siblings[i].level;
            // 更新子节点层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i, parentCid: pCid, catLevel: catLevel });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      console.log("updateNodes: ", this.updateNodes);
    },
    saveBatch() {
      this.$http({
        url: this.$http.adornUrl('/product/category/updateBatch'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "保存成功"
        });
        this.getMenuList();
        this.expandedKeys = this.pCids;

        this.updateNodes = [];
        this.pCids = [];
      });
    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({ catId: node.childNodes[i].data.catId, catLevel: node.childNodes[i].level });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
  },
};
</script>

<style>
</style>